package com.lyw.db

import android.annotation.SuppressLint
import android.content.Context
import androidx.room.Room
import androidx.room.migration.Migration
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import com.lyw.db.entites.Idiom
import com.lyw.db.entites.Knowledge
import com.lyw.db.entites.Poem
import com.lyw.db.entites.PoemOrTag
import com.lyw.db.entites.PoemTag
import com.lyw.db.entites.Question
import com.lyw.db.entites.Sentence
import com.lyw.db.entites.Twister
import com.lyw.db.entites.Wisecrack
import com.lyw.db.entites.Writer
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.lang.IllegalStateException
import java.lang.reflect.Type

@SuppressLint("StaticFieldLeak")
object DatabaseProvider {
    private var INSTANCE: AppDatabase? = null
    private lateinit var mContext:Context
    fun init(context: Context){
        mContext=context.applicationContext

    }
    fun getDatabase(): AppDatabase {
        if (!::mContext.isInitialized){
            throw IllegalStateException("must call init ");
        }
        if (INSTANCE == null) {
            synchronized(AppDatabase::class) {
                INSTANCE = Room.databaseBuilder(
                    mContext.applicationContext,
                    AppDatabase::class.java,
                    "knowledge_db"
                ).addMigrations(Migration(1,2){database->
                    // 显式地添加新列，尽管 Room 通常应该能够自动处理这种情况
//                    database.execSQL("ALTER TABLE twister ADD COLUMN IF NOT EXISTS content2 TEXT")
                    database.execSQL("ALTER TABLE questions ADD COLUMN topType TEXT")
                    database.execSQL("ALTER TABLE questions ADD COLUMN subType TEXT")
//                    database.execSQL("DELETE FROM questions")
                }, Migration(2,3){database->
                    // 重命名列
                    database.execSQL("ALTER TABLE poem RENAME COLUMN writerId TO writer_id")
                    database.execSQL("DELETE FROM poem")
                },Migration(3,4){database->
                    database.execSQL("ALTER TABLE poem ADD COLUMN user_like INT DEFAULT 0")
                }).build()
            }
        }
        return INSTANCE!!
    }


    suspend fun insertQuestionsFromJson(topType:String,subType:String,json: String,knowledgeType:Int) {

        val questions: QuestionInfo = Gson().fromJson(json,QuestionInfo::class.java)
//        LogUtils.d(questions.questions.size)
        //android-framework
        if (questions.questions.isNotEmpty()) {
            var learn_type = questions.learn_type
            var learnType = LearnType.all
            var learnSubType = ""
            if (!learn_type.isNullOrEmpty()){
                var types = learn_type.split("-")
                LearnType.values().find {
                    it.name==types[0]
                }?.let {
                    learnType=it
                }
                if (types.size>1){
                    learnSubType = types[1]
                }
            }
            var questionDb = questions.questions.map {
                var qs = StringBuilder()
                it.options?.forEach { option ->
                    qs.append(option)
                    qs.append("|")
                }?.let {
                    qs.deleteCharAt(qs.length - 1)
                }
                var type = QuestionType.Selection.ordinal
                QuestionType.values().find { type ->
                    type.typeName == it.type
                }?.let {
                    type = it.ordinal
                }

//                LogUtils.d(qs.toString())
                var q= Question(
                    type = type,
                    knowledgeType = knowledgeType,
//                    knowledgeSubType = learnSubType,
                    topType=topType,
                    subType = subType,
                    question = it.question,
                    option = qs.toString(),
                    answer = it.answer
                )
//                LogUtils.d(q)
                q
            }
            getDatabase().questionDao().insertAll(*(questionDb.toTypedArray()))
        }
    }

}